<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增班级信息')" />
    <th:block th:include="include :: bootstrap-select-css" />
    <th:block th:include="include :: summernote-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <th:block th:include="include :: bootstrap-editable-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-classInfo-add">
            <div class="tabs-container">
                <ul class="nav nav-tabs">
                    <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">基本信息</a>
                    </li>
                    <li class=""><a id="question_tab" data-toggle="tab" href="#tab-2" aria-expanded="false">名言警句</a>
                    </li>
                </ul>
                <div class="tab-content">
                    <div id="tab-1" class="tab-pane active">
                        <div class="panel-body">
                            <div class="form-group">
                                <input id="id" type="hidden" value="">
                                <label class="col-sm-3 control-label is-required">班级名称：</label>
                                <div class="col-sm-8">
                                    <input name="className" class="form-control" type="text" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label is-required">班主任：</label>
                                <div class="col-sm-8">
                                    <select name="teacherId" id="answerStatus" class="form-control m-b" th:with="type=${@teacher.getTeacherList()}" required>
                                        <option th:each="teacher : ${type}" th:text="${teacher.userName}" th:value="${teacher.userId}"></option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label is-required">年级：</label>
                                <div class="col-sm-8">
                                    <input id="gradeName" name="gradeName"  type="hidden">
                                    <select class='form-control selectpicker' data-live-search="false" id='gradeId' name='gradeId' required>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label is-required">所在教室：</label>
                                <div class="col-sm-8">
                                    <select class='form-control selectpicker' data-live-search="true" name="roomId" th:with="type=${@roomInfo.getRoomListDict()}" required>
                                        <option th:each="dict : ${type}" th:text="${dict.roomName}" th:value="${dict.id}" ></option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">班级风采：</label>
                                <div class="col-sm-8">
                                    <div class="ibox-content no-padding">
                                        <input id="description" name="description" type="hidden">
                                        <div class="summernote" id="content" required>

                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">班级照片：</label>
                                <div class="col-sm-8">
                                    <input type="hidden"  name="img" id="img_url" value="">
                                    <div class="file-loading">
                                        <input type="file"  name="file" id="img">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-offset-5 col-sm-10">
                                    <button type="button" class="btn btn-sm btn-primary" onclick="saveClassInfo()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--名言警句设置-->
                    <div id="tab-2" class="tab-pane">
                        <div class="panel-body">
                            <div class="panel-heading">
                                <a class="btn btn-success" href="javascript:void(0)" onclick="addContent()">添加</a>
                            </div>

                            <div id="wisdomContent">
                                <div class="form-group wisdomContent">
                                    <label class="col-sm-2 control-label">序号：</label>
                                    <div class="col-sm-1">
                                        <input name="sortNo" class="form-control sortNo" type="number">
                                    </div>

                                    <label class="col-sm-1 control-label">内容：</label>

                                    <div class="col-sm-5">
                                        <textarea name="content" class="form-control content" style="width: 310px;" rows="5" maxlength="80"></textarea>
                                    </div>
                                    <div class="col-sm-1">
                                        <a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeContent(this)">删除</a>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-offset-5 col-sm-10">
                                    <button type="button" class="btn btn-sm btn-primary" onclick="saveWisdom()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                                </div>
                            </div>
                        </div>

                    </div>

                </div>
            </div>

        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-select-js" />
    <th:block th:include="include :: summernote-js" />
    <th:block th:include="include :: bootstrap-fileinput-js" />
    <th:block th:include="include :: bootstrap-table-editable-js" />
    <script type="text/javascript">
        var prefix = ctx + "school/classInfo";
        var List = new Array();
        $("#form-classInfo-add").validate({
            focusCleanup: true
        });
        $(document).ready(function () {
            $('.summernote').summernote({
                lang: 'zh-CN',
                height: 100,
                followingToolbar: false,
                callbacks: {
                    onImageUpload: function (files) {
                        sendFile(files[0], this);
                    }
                }
            });
        });
        // 上传文件
        function sendFile(file, obj) {
            var data = new FormData();
            data.append("file", file);
            $.ajax({
                type: "POST",
                url: ctx + "common/upload",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $(obj).summernote('editor.insertImage', result.url, result.fileName);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function(error) {
                    $.modal.alertWarning("图片上传失败。");
                }
            });
        }
        function saveClassInfo() {
            if ($.validate.form()) {
                var sHTML = $('.summernote').summernote('code');
                $("#description").val(sHTML);
                for (let i = 0; i < List.length ; i++) {
                    var url = $("#img_url").val();
                    if(url == null || url == undefined){
                        url=List[i].url;
                    }else {
                        url = url+","+List[i].url;
                    }
                    $("#img_url").val(url);
                }
                var config = {
                    url:  prefix + "/add",
                    type: "post",
                    dataType: "json",
                    data: $('#form-classInfo-add').serialize(),
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍后...");
                    },
                    success: function(result) {
                        console.info(result);
                        $("#id").val(result.data);
                        $.modal.closeLoading();
                        $("#question_tab").tab('show');
                    }
                };
                $.ajax(config)
            }
        }

        /*用户管理-新增-选择部门树*/
        function selectDeptTree() {
            var treeId = $("#treeId").val();
            var deptId = $.common.isEmpty(treeId) ? "100" : $("#treeId").val();
            var url = ctx + "system/dept/selectDeptTree/" + deptId;
            var options = {
                title: '选择部门',
                width: "380",
                url: url,
                callBack: doSubmit
            };
            $.modal.openOptions(options);
        }
        function doSubmit(index, layero){
            var tree = layero.find("iframe")[0].contentWindow.$._tree;
            var body = layer.getChildFrame('body', index);
            $("#treeId").val(body.find('#treeId').val());
            $("#treeName").val(body.find('#treeName').val());
            layer.close(index);
        }
        $(document).ready(function(){

            $("#img").fileinput({
                'theme': 'explorer-fas',
                'uploadUrl': '/common/upload',
                //'deleteUrl': deleteImg(),
                'overwriteInitial': false,
                'maxFileCount':5,
                'elCaptionText':'sss',
                'showUpload':false,
                'initialPreviewAsData': true,
                //'initialPreview': imgData,
                //'initialPreviewConfig': config

            }).on("filebatchselected", function(event, files) { // 选择文件后回调
                $("#img").fileinput("upload");
            }).on("fileuploaded", function(event, data, previewId, index) { // 上传成功回调
                if(data.response.code == 0){
                    List.push({ "url": data.response.url, "previewId": previewId })
                }
            }).on("filesuccessremove", function (event, data, previewId, index) {
                List.splice(previewId,1);
            });

            $.ajax({
                type: "post",
                url:ctx + "school/grade/getGradeList",
                async:false,
                dataType: "json",
                success: function(res){
                    if (null != res) {
                        var html = '';
                        Object.keys(res).forEach(function(key){
                            html += '<option value="' + res[key].id + '" data-tokens="'+ res[key].gradeName+'">' + res[key].gradeName+ '</option>';
                        });
                        $("#gradeId").html(html);
                        //必须加，刷新select
                        $("#gradeId").selectpicker('refresh');
                    }
                }
            });
        })


        function saveWisdom() {
            if($("#id").val().length == 0){
                $.modal.alertWarning("请先保存基本信息!");
                return;
            }

            var data = $(".wisdomContent")
            var json = {};
            json["classId"] = $("#id").val();
            for (let i = 0; i < data.length ; i++) {
                var wisdom = {};
                var sortNo = $(data[i]).find('.sortNo').val();
                var content = $(data[i]).find('.content').val();
                if(sortNo.length == 0 || content.length == 0){
                    $.modal.alertWarning("请填写完整内容!");
                    return;
                }
                json["wisdomList["+i+"].sortNo"]=sortNo;
                json["wisdomList["+i+"].content"]=content;
                json["wisdomList["+i+"].classId"]=$("#id").val();
            }
            $.operate.save(prefix + "/saveWisdom", json);
        }

        function addContent() {
            if($('.wisdomContent').length ==10){
                $.modal.alertWarning("最多添加10条名言警句!");
                return;
            }
            var content = ' <div class="form-group wisdomContent">\n' +
                '                                    <label class="col-sm-2 control-label">序号：</label>\n' +
                '\n' +
                '                                    <div class="col-sm-1">\n' +
                '                                        <input name="content sortNo" class="form-control sortNo" type="number">\n' +
                '                                    </div>\n' +
                '\n' +
                '                                    <label class="col-sm-1 control-label">内容：</label>\n' +
                '\n' +
                '                                    <div class="col-sm-5">\n' +
                '                                        <textarea name="content" class="form-control content" style="width: 310px;" rows="5" maxlength="80"></textarea>\n' +
                '                                    </div>\n' +
                '                                    <div class="col-sm-1">\n' +
                '                                        <a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeContent(this)">删除</a>\n' +
                '                                    </div>\n' +
                '                                </div>';

            $("#wisdomContent").append(content);
        }

        function removeContent(obj) {
            $(obj).parents('.wisdomContent').remove();
        }

    </script>
</body>
</html>